package com.starrocks.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 * 用于全量同步等异步任务
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "sync.thread-pool")
public class ThreadPoolConfig {
    
    /**
     * 核心线程数（默认2）
     */
    private int corePoolSize = 2;
    
    /**
     * 最大线程数（默认5）
     */
    private int maxPoolSize = 5;
    
    /**
     * 队列容量（默认50）
     */
    private int queueCapacity = 50;
    
    /**
     * 线程空闲时间（秒，默认60）
     */
    private int keepAliveSeconds = 60;
    
    /**
     * 线程名称前缀
     */
    private String threadNamePrefix = "SyncPool-";
    
    /**
     * 拒绝策略：
     * - ABORT: 抛出异常（默认）
     * - CALLER_RUNS: 调用者线程执行
     * - DISCARD: 丢弃任务
     * - DISCARD_OLDEST: 丢弃队列最老任务
     */
    private String rejectedPolicy = "CALLER_RUNS";
    
    /**
     * 创建全量同步线程池
     */
    @Bean(name = "fullSyncExecutor")
    public ThreadPoolTaskExecutor fullSyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 队列容量
        executor.setQueueCapacity(queueCapacity);
        // 线程空闲时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        
        // 设置拒绝策略
        switch (rejectedPolicy.toUpperCase()) {
            case "CALLER_RUNS":
                executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
                break;
            case "DISCARD":
                executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
                break;
            case "DISCARD_OLDEST":
                executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
                break;
            case "ABORT":
            default:
                executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
                break;
        }
        
        // 等待所有任务完成后关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间（秒）
        executor.setAwaitTerminationSeconds(60);
        
        // 初始化
        executor.initialize();
        
        log.info("✅ 全量同步线程池初始化完成 - 核心线程数: {}, 最大线程数: {}, 队列容量: {}, 拒绝策略: {}", 
            corePoolSize, maxPoolSize, queueCapacity, rejectedPolicy);
        
        return executor;
    }
}

